#include <ctype.h>
#include "client.h"

int main()
{
    int server_fifo_fd,client_fifo_fd;
    struct data_to_pass_st my_data;
    int time_to_send;
    char client_fifo[256];
    
    server_fifo_fd = open(SERVER_FIFO_NAME,O_WRONLY);//打开服务器的写管道口
    if (server_fifo_fd == -1) {
        perror("server open failure");
        exit(EXIT_FAILURE);
    }
//    printf ("server fifo is opened\n");

    my_data.client_pid = getpid();
    sprintf(client_fifo,CLIENT_FIFO_NAME,my_data.client_pid);
    printf("now client_id:[%s]\n",client_fifo);
    if (mkfifo(client_fifo,0777) == -1){
        fprintf(stderr,"Sorry,can't make %s\n",client_fifo);
        exit(EXIT_FAILURE);
    }//创建一个管道

//    for (time_to_send = 0;time_to_send < 5;time_to_send ++){
        sprintf (my_data.some_data,"Hello form [%d]",my_data.client_pid);
        printf("[%d] sent [%s]\n",my_data.client_pid,my_data.some_data);
        write(server_fifo_fd,&my_data,sizeof(my_data));//数据封装，写入到服务器的管道中
        client_fifo_fd = open(client_fifo,O_RDONLY);//打开自己的管道，以读堵塞的方式
        if (client_fifo_fd != -1) {
            printf ("open client id success\n");    
            if (read(client_fifo_fd,&my_data,sizeof(my_data)) > 0) {
                printf("Received :[%s]\n",my_data.some_data);;
            }else{
                printf("client read failurei\n");
            }
            sleep(2);
            close(client_fifo_fd);
        }else{
            perror("client fifo open failure");    
        }
//  }//发了五遍
    close(server_fifo_fd);
    unlink(client_fifo);
    exit(EXIT_SUCCESS);

}
